<template>
  <div class="inventory-check-container">
    <h2>库存盘点</h2>

    <!-- 搜索栏 -->
    <div class="search-wrapper">
      <el-input
        v-model="searchText"
        placeholder="请输入储位名称搜索"
        style="width: 300px"
        clearable
        @keyup.enter="handleSearch">
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleSearch">
        <el-icon><Search /></el-icon>搜索
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      :data="filteredTableData"
      border
      style="width: 100%"
      v-loading="loading">
      <el-table-column prop="storageName" label="储位名称" align="center" />
      <el-table-column prop="capacity" label="储位容量（KG）" align="center" />
      <el-table-column prop="inventory" label="现有库存（KG）" align="center" />
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { get } from '@/api/api'

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 搜索文本
const searchText = ref('')

// 过滤后的表格数据
const filteredTableData = ref([])

// 获取库存盘点数据
const fetchInventoryData = async () => {
  loading.value = true
  try {
    const res = await get('/storage/storage/inventory')
    console.log('接口返回数据:', res) // 打印接口返回数据
    if (res.data) {
      tableData.value = res.data
      filteredTableData.value = res.data // 初始化时显示全部数据
    } else {
      ElMessage.error('获取数据失败')
    }
  } catch (error) {
    console.error('请求失败:', error)
    ElMessage.error('请求失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  if (!searchText.value) {
    filteredTableData.value = tableData.value // 如果搜索框为空，显示全部数据
  } else {
    filteredTableData.value = tableData.value.filter(item =>
      item.storageName.toLowerCase().includes(searchText.value.toLowerCase())
    )
  }
}

// 初始化时加载数据
onMounted(() => {
  fetchInventoryData()
})
</script>

<style scoped>
.inventory-check-container {
  padding: 20px;
  background: white;
  border-radius: 4px;
}

h2 {
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: bold;
}

.search-wrapper {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}
</style>